
#include "Battery.h"



long time = 0;         // the last time the output pin was toggled
long debounce = 500;   // the debounce time, increase if the output flickers
 
int switchState = CLOSED; 
int previousSwitchState = OPEN; 
Battery battery;

void loop()
{
  processSwitchStatus(); 

  displayBatteryStatus();
  //displayDateTemp();
  
  manageSleepCycle();
  
   //Un pequeño delay para no volver loco al puerto serie
  //delay(LOOP_DELAY);
 
}

void processSwitchStatus()
{
  int switchReading = digitalRead(FLOAT_SWITCH_PIN);

     if (switchState == OPEN)
       Serial.println("Switch En seco...");
     else
       Serial.println("Switch Flontando...");

 
  // If the switch changed, due to bounce or pressing...
  if (switchReading != previousSwitchState)
    time = millis(); // reset the debouncing timer
 
   //Comprobamos si lleva suficiente tiempo en este estado
  if ((millis() - time) > debounce)
  {
     // whatever the switch is at, its been there for a long time
     // so lets settle on it!
     switchState = switchReading;
     //Encendemos el led si el flotador queda en estado abierto, es decir no flota
     int ledState = (switchState == OPEN) ? HIGH : LOW;
     digitalWrite(SWITCH_LED_PIN, switchState);
     
     if (switchState == OPEN)
       Serial.println("Estable En seco...");
     else
       Serial.println("Estable Flontando...");
  }
  previousSwitchState = switchReading; 
}



void displayBatteryStatus()
{
  battery.update();
  //battery.ledflashStatus(POWER_LED_PIN, LED_FLASHES_FOR_FULL);
  float voltage = battery.getVoltage();
  int percentage = battery.getPercentage();
  char* CS = battery.getChStatus();
  bool ch = battery.isCharging();
  
  if (strcmp(CS, "done") == 0)
    digitalWrite(POWER_LED_PIN, HIGH);
  else
    digitalWrite(POWER_LED_PIN, LOW);
  
  Serial.print("battery: ");
  Serial.print(String(voltage,4));
  Serial.print("V  -> ");
  Serial.print(percentage);
  Serial.print("%     Charge Status: ");
  Serial.print(CS);
  Serial.println();
}

void displayDateTemp()
{
      RTC.convertTemperature();          //convert current temperature into registers
      float temp = RTC.getTemperature(); //Read temperature sensor value

    DateTime now = RTC.now(); //get the current date-time    
    if((now.second()) !=  prevSecond )
    {
      //print only when there is a change
      Serial.print(now.year(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.date(), DEC);
      Serial.print(' ');
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.print("   ");
      Serial.print(temp);
      Serial.print(" deg C");
      Serial.println();
    }
    prevSecond = now.second();
}



